<template>
  <div class="normal-admin-container">
    <el-header class="header">
      <div class="header-left">
        <h2>普通管理员系统</h2>
      </div>
      <div class="header-center">
        <el-button-group>
          <el-button 
            @click="refreshCurrentTab"
            :icon="Refresh"
          >
            刷新
          </el-button>
        </el-button-group>
      </div>
      <div class="header-right">
        <span class="welcome">欢迎，{{ adminInfo.realName }}</span>
        <el-button type="danger" @click="handleLogout">退出登录</el-button>
      </div>
    </el-header>

    <el-main class="main-content">
      <!-- 标签页切换 -->
      <el-tabs v-model="activeTab" class="admin-tabs">

        <el-tab-pane label="医生管理" name="doctors">
          <!-- 医生管理内容 -->
          <div class="tab-content">
            <!-- 搜索和操作区域 -->
            <div class="toolbar">
              <div class="search-area">
                <el-input
                  v-model="doctorSearchForm.realName"
                  placeholder="医生姓名"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-input
                  v-model="doctorSearchForm.phone"
                  placeholder="联系电话"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-input
                  v-model="doctorSearchForm.email"
                  placeholder="电子邮箱"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-select
                  v-model="doctorSearchForm.gender"
                  placeholder="性别"
                  style="width: 120px; margin-right: 10px"
                  clearable
                >
                  <el-option label="男" :value="1" />
                  <el-option label="女" :value="2" />
                </el-select>
                <el-input
                  v-model="doctorSearchForm.practiceScope"
                  placeholder="执业范围"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-select
                  v-model="doctorSearchForm.level"
                  placeholder="等级"
                  style="width: 120px; margin-right: 10px"
                  clearable
                >
                  <el-option label="Lv.1" :value="1" />
                  <el-option label="Lv.2" :value="2" />
                  <el-option label="Lv.3" :value="3" />
                  <el-option label="Lv.4" :value="4" />
                  <el-option label="Lv.5" :value="5" />
                  <el-option label="Lv.6" :value="6" />
                  <el-option label="Lv.7" :value="7" />
                  <el-option label="Lv.8" :value="8" />
                  <el-option label="Lv.9" :value="9" />
                  <el-option label="Lv.10" :value="10" />
                </el-select>
                <el-select
                  v-model="doctorSearchForm.hospitalName"
                  placeholder="医院名称"
                  style="width: 200px; margin-right: 10px"
                  clearable
                >
                  <el-option 
                    v-for="hospital in hospitalList" 
                    :key="hospital" 
                    :label="hospital" 
                    :value="hospital" 
                  />
                </el-select>
                <el-button type="primary" @click="handleDoctorSearch">搜索</el-button>
                <el-button @click="resetDoctorSearch">重置</el-button>
              </div>
              
              <div class="action-area">
                <el-button type="success" @click="showCreateDoctorDialog">新增医生</el-button>
                <el-button type="warning" @click="showDeletedDoctors">查看已删除医生</el-button>
                <el-button type="danger" @click="handleBatchDeleteDoctor" :disabled="!selectedDoctors.length">
                  批量删除
                </el-button>
              </div>
            </div>

            <!-- 医生数据表格 -->
            <el-table
              :data="doctorList"
              @selection-change="handleDoctorSelectionChange"
              v-loading="doctorLoading"
              border
              style="width: 100%"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="username" label="用户名" width="120" />
              <el-table-column prop="realName" label="医生姓名" width="120" />
              <el-table-column prop="phone" label="联系电话" width="130" />
              <el-table-column prop="email" label="电子邮箱" width="180" />
              <el-table-column prop="gender" label="性别" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.gender === 1 ? 'primary' : row.gender === 2 ? 'success' : 'info'">
                    {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未设置' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="practiceScope" label="执业范围" width="120">
                <template #default="{ row }">
                  {{ row.practiceScope || '未设置' }}
                </template>
              </el-table-column>
              <el-table-column prop="hospitalName" label="所属医院" width="180">
                <template #default="{ row }">
                  {{ row.hospitalName || '未设置' }}
                </template>
              </el-table-column>
              <el-table-column prop="points" label="积分" width="80">
                <template #default="{ row }">
                  {{ row.points }}
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="280" fixed="right">
                <template #default="{ row }">
                  <el-button type="primary" size="small" @click="showEditDoctorDialog(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteDoctor(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 医生分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="doctorPagination.current"
                v-model:page-size="doctorPagination.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="doctorPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleDoctorSizeChange"
                @current-change="handleDoctorCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="活动管理" name="activities">
          <!-- 活动管理内容 -->
          <div class="tab-content">
            <!-- 搜索和操作区域 -->
            <div class="toolbar">
              <div class="search-area">
                <el-input
                  v-model="activitySearchForm.name"
                  placeholder="活动名称"
                  style="width: 200px; margin-right: 10px"
                  clearable
                />
                <el-input
                  v-model="activitySearchForm.location"
                  placeholder="活动地点"
                  style="width: 200px; margin-right: 10px"
                  clearable
                />
                <el-date-picker
                  v-model="activitySearchForm.startTime"
                  type="datetime"
                  placeholder="开始时间"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-date-picker
                  v-model="activitySearchForm.endTime"
                  type="datetime"
                  placeholder="结束时间"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-button type="primary" @click="handleActivitySearch">搜索</el-button>
                <el-button @click="resetActivitySearch">重置</el-button>
              </div>
              
              <div class="action-area">
                <el-button type="success" @click="showCreateActivityDialog">新增活动</el-button>
                <el-button type="danger" @click="handleBatchDeleteActivity" :disabled="!selectedActivities.length">
                  批量删除
                </el-button>
              </div>
            </div>

            <!-- 活动数据表格 -->
            <el-table
              :data="activityList"
              @selection-change="handleActivitySelectionChange"
              v-loading="activityLoading"
              border
              style="width: 100%"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="活动名称" width="200" />
              <el-table-column prop="cover" label="封面图片" width="120">
                <template #default="{ row }">
                  <div v-if="row.cover" style="position: relative;">
                    <el-image
                      :src="processCoverUrl(row.cover)"
                      style="width: 80px; height: 60px"
                      fit="cover"
                      :preview-src-list="[processCoverUrl(row.cover)]"
                      @error="handleImageError"
                    />
                    <span class="image-error" style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #999; display: none;">加载失败</span>
                  </div>
                  <span v-else>无图片</span>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="活动描述" width="300" show-overflow-tooltip />
              <el-table-column prop="location" label="活动地点" width="150" />
              <el-table-column prop="points" label="活动积分" width="100">
                <template #default="{ row }">
                  <span class="points">{{ row.points || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column label="报名统计" width="120">
                <template #default="{ row }">
                  <div v-if="row.registrationStats">
                    <div>总报名: {{ row.registrationStats.totalRegistrations || 0 }}</div>
                  </div>
                  <span v-else>-</span>
                </template>
              </el-table-column>
              <el-table-column prop="startTime" label="开始时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.startTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="endTime" label="结束时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.endTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="createdAt" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="320" fixed="right">
                <template #default="{ row }">
                  <el-button type="info" size="small" @click="showRegistrationsDialog(row)">
                    查看报名
                  </el-button>
                  <el-button type="success" size="small" @click="showAuditDialog(row)">
                    审核
                  </el-button>
                  <el-button type="primary" size="small" @click="showEditActivityDialog(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeleteActivity(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 活动分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="activityPagination.current"
                v-model:page-size="activityPagination.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="activityPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleActivitySizeChange"
                @current-change="handleActivityCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="推文管理" name="push">
          <!-- 推文管理内容 -->
          <div class="tab-content">
            <!-- 搜索和操作区域 -->
            <div class="toolbar">
              <div class="search-area">
                <el-input
                  v-model="pushSearchForm.title"
                  placeholder="推文标题"
                  style="width: 200px; margin-right: 10px"
                  clearable
                />
                <el-input
                  v-model="pushSearchForm.publisherName"
                  placeholder="发布者姓名"
                  style="width: 150px; margin-right: 10px"
                  clearable
                />
                <el-select
                  v-model="pushSearchForm.status"
                  placeholder="推文状态"
                  style="width: 120px; margin-right: 10px"
                  clearable
                >
                  <el-option label="草稿" :value="0" />
                  <el-option label="已发布" :value="1" />
                  <el-option label="已撤回" :value="2" />
                </el-select>
                <el-date-picker
                  v-model="pushSearchForm.startTime"
                  type="datetime"
                  placeholder="开始时间"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-date-picker
                  v-model="pushSearchForm.endTime"
                  type="datetime"
                  placeholder="结束时间"
                  style="width: 180px; margin-right: 10px"
                  clearable
                />
                <el-button type="primary" @click="handlePushSearch">搜索</el-button>
                <el-button @click="resetPushSearch">重置</el-button>
              </div>
              
              <div class="action-area">
                <el-button type="success" @click="showCreatePushDialog">新增推文</el-button>
                <el-button type="danger" @click="handleBatchDeletePush" :disabled="!selectedPushes.length">
                  批量删除
                </el-button>
              </div>
            </div>

            <!-- 推文数据表格 -->
            <el-table
              :data="pushList"
              @selection-change="handlePushSelectionChange"
              v-loading="pushLoading"
              border
              style="width: 100%"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="title" label="标题" width="200" show-overflow-tooltip />
              <el-table-column prop="summary" label="简介" width="250" show-overflow-tooltip />
              <el-table-column prop="coverImage" label="封面" width="120">
                <template #default="{ row }">
                  <div v-if="row.coverImage" style="position: relative;">
                    <el-image
                      :src="processImageUrl(row.coverImage)"
                      style="width: 80px; height: 60px"
                      fit="cover"
                      :preview-src-list="[processImageUrl(row.coverImage)]"
                      @error="handleImageError"
                    />
                  </div>
                  <span v-else>无封面</span>
                </template>
              </el-table-column>
              <el-table-column prop="publisherName" label="发布者" width="120" />
              <el-table-column prop="viewCount" label="浏览次数" width="100" />
              <el-table-column prop="likeCount" label="点赞数" width="80" />
              <el-table-column prop="commentCount" label="评论数" width="80" />
              <el-table-column prop="status" label="状态" width="100">
                <template #default="{ row }">
                  <el-tag :type="getPushStatusType(row.status)" class="push-status-tag">
                    {{ getPushStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建时间" width="160">
                <template #default="{ row }">
                  {{ formatDateTime(row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="350" fixed="right">
                <template #default="{ row }">
                  <el-button type="info" size="small" @click="showPushDetail(row)">
                    查看详情
                  </el-button>
                  <el-button 
                    v-if="row.status === 0" 
                    type="success" 
                    size="small" 
                    @click="handlePublishPush(row)"
                  >
                    发布
                  </el-button>
                  <el-button 
                    v-if="row.status === 1" 
                    type="warning" 
                    size="small" 
                    @click="handleWithdrawPush(row)"
                  >
                    撤回
                  </el-button>
                  <el-button type="primary" size="small" @click="showEditPushDialog(row)">
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDeletePush(row)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 推文分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="pushPagination.current"
                v-model:page-size="pushPagination.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="pushPagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handlePushSizeChange"
                @current-change="handlePushCurrentChange"
              />
            </div>
          </div>
        </el-tab-pane>

        <el-tab-pane label="反馈处理" name="feedback">
          <!-- 反馈处理内容 -->
          <div class="tab-content">
            <div class="feedback-management-content">
              <div class="feedback-header">
                <h3>反馈处理管理</h3>
                <p>管理医生提交的反馈信息，进行审核和回复</p>
              </div>
              
              <div class="feedback-actions">
                <el-button type="primary" @click="goToFeedbackManagement">
                  <el-icon><ChatDotRound /></el-icon>
                  进入反馈处理
                </el-button>
                <el-button @click="refreshFeedbackData">
                  <el-icon><Refresh /></el-icon>
                  刷新数据
                </el-button>
              </div>
              
              <!-- 反馈统计卡片 -->
              <el-row :gutter="20" class="feedback-stats">
                <el-col :span="6">
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-number">{{ feedbackStats.total || 0 }}</div>
                      <div class="stat-label">总反馈数</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-number pending">{{ feedbackStats.pending || 0 }}</div>
                      <div class="stat-label">待处理</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-number processing">{{ feedbackStats.processing || 0 }}</div>
                      <div class="stat-label">处理中</div>
                    </div>
                  </el-card>
                </el-col>
                <el-col :span="6">
                  <el-card class="stat-card">
                    <div class="stat-content">
                      <div class="stat-number resolved">{{ feedbackStats.resolved || 0 }}</div>
                      <div class="stat-label">已解决</div>
                    </div>
                  </el-card>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-main>

    <!-- 医生新增/编辑对话框 -->
    <el-dialog
      v-model="doctorDialogVisible"
      :title="doctorDialogTitle"
      width="600px"
      @close="resetDoctorForm"
    >
      <el-form
        ref="doctorFormRef"
        :model="doctorForm"
        :rules="doctorFormRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username" v-if="!isEditDoctor">
          <el-input v-model="doctorForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEditDoctor">
          <el-input v-model="doctorForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="医生姓名" prop="realName">
          <el-input v-model="doctorForm.realName" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="doctorForm.phone" />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="doctorForm.email" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="doctorForm.gender" style="width: 100%">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="doctorForm.address" />
        </el-form-item>
        <el-form-item label="执业范围" prop="practiceScope">
          <el-input v-model="doctorForm.practiceScope" />
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalName">
          <el-input 
            v-model="doctorForm.hospitalName" 
            disabled 
            placeholder="自动设置为当前管理员"
          />
          <div style="font-size: 12px; color: #909399; margin-top: 4px;">
            所属医院将自动设置为：{{ adminInfo.realName }}
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="doctorDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDoctorSubmit" :loading="doctorSubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 已删除医生对话框 -->
    <el-dialog
      v-model="deletedDoctorsDialogVisible"
      title="已删除医生管理"
      width="1200px"
      @close="deletedDoctorsPagination.current = 1"
    >
      <div class="deleted-doctors-content">
        <!-- 已删除医生表格 -->
        <el-table
          :data="deletedDoctorsList"
          v-loading="deletedDoctorsLoading"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="realName" label="医生姓名" width="120" />
          <el-table-column prop="phone" label="联系电话" width="130" />
          <el-table-column prop="email" label="邮箱" width="180" />
          <el-table-column prop="gender" label="性别" width="80">
            <template #default="{ row }">
              <el-tag :type="row.gender === 1 ? 'primary' : row.gender === 2 ? 'success' : 'info'">
                {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="practiceScope" label="执业范围" width="120" />
          <el-table-column prop="level" label="等级" width="80">
            <template #default="{ row }">
              Lv.{{ row.level }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="deleteTime" label="删除时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.deleteTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="success" size="small" @click="handleRestoreDoctor(row.id)">
                恢复
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 已删除医生分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="deletedDoctorsPagination.current"
            v-model:page-size="deletedDoctorsPagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="deletedDoctorsPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleDeletedDoctorsSizeChange"
            @current-change="handleDeletedDoctorsCurrentChange"
          />
        </div>
      </div>
    </el-dialog>



    <!-- 活动新增/编辑对话框 -->
    <el-dialog
      v-model="activityDialogVisible"
      :title="activityDialogTitle"
      width="800px"
      @close="resetActivityForm"
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityFormRules"
        label-width="120px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="activityForm.name" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="封面图片" prop="cover">
          <div class="cover-upload">
            <el-upload
              ref="coverUploadRef"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleCoverChange"
              accept="image/*"
              class="cover-uploader"
            >
              <img v-if="activityForm.cover" :src="activityForm.cover" class="cover-image" />
              <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="cover-tips">
              <p>支持 jpg, jpeg, png, gif, bmp 格式</p>
              <p>文件大小不超过 5MB</p>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="活动描述" prop="description">
          <el-input
            v-model="activityForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动描述"
          />
        </el-form-item>

        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        
        <el-form-item label="活动积分" prop="points">
          <el-input-number 
            v-model="activityForm.points" 
            :min="0" 
            :max="1000" 
            controls-position="right"
            placeholder="请设置活动积分奖励"
            style="width: 200px"
          />
          <span style="margin-left: 10px; color: #909399; font-size: 12px;">
            参与此活动的医生将获得的积分（审核时可调整）
          </span>
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="activityForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="activityForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="activityDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleActivitySubmit" :loading="activitySubmitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 用户报名管理对话框 -->
    <el-dialog
      v-model="registrationsDialogVisible"
      :title="`${selectedActivity?.name} - 报名用户管理`"
      width="1200px"
      @close="resetRegistrations"
    >
      <div class="registrations-content">
        <div class="registrations-header">
          <div class="activity-info">
            <h4>{{ selectedActivity?.name }}</h4>
            <p><strong>地点：</strong>{{ selectedActivity?.location }}</p>
            <p><strong>时间：</strong>{{ formatDateTime(selectedActivity?.startTime) }} - {{ formatDateTime(selectedActivity?.endTime) }}</p>
          </div>
          <div class="batch-actions">
            <!-- 审核功能已移除 -->
          </div>
        </div>

        <el-table
          :data="registrationsList"
          v-loading="registrationsLoading"
          border
          style="width: 100%"
        >
          <!-- 移除选择列，因为不再需要批量审核 -->
          <el-table-column prop="patientName" label="患者姓名" width="120" />
          <el-table-column prop="patientGender" label="性别" width="80">
            <template #default="{ row }">
              {{ row.patientGender === 1 ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="patientAge" label="年龄" width="80" />
          <el-table-column prop="patientIdCard" label="身份证号" width="180" show-overflow-tooltip />
          <el-table-column prop="patientPhone" label="联系电话" width="130" />
          <el-table-column prop="patientAllergicHistory" label="过敏史" width="120" show-overflow-tooltip />
          <el-table-column prop="patientMedicalHistory" label="病史" width="120" show-overflow-tooltip />
          <el-table-column prop="registrationTime" label="报名时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.registrationTime) }}
            </template>
          </el-table-column>
        
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="registrationsTotal > 0"
          v-model:current-page="registrationsCurrentPage"
          v-model:page-size="registrationsPageSize"
          :total="registrationsTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRegistrationsSizeChange"
          @current-change="handleRegistrationsCurrentChange"
          style="margin-top: 20px; text-align: right;"
        />
      </div>
    </el-dialog>

    <!-- 推文详情对话框 -->
    <el-dialog
      v-model="pushDetailDialogVisible"
      title="推文详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedPush" class="push-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="ID">{{ selectedPush.id }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getPushStatusType(selectedPush.status)" class="push-status-tag">
              {{ getPushStatusText(selectedPush.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标题" :span="2">{{ selectedPush.title }}</el-descriptions-item>
          <el-descriptions-item label="简介" :span="2">{{ selectedPush.summary }}</el-descriptions-item>
          <el-descriptions-item label="封面" :span="2" v-if="selectedPush.coverImage">
            <el-image
              :src="processImageUrl(selectedPush.coverImage)"
              style="width: 200px; height: 150px"
              fit="cover"
              :preview-src-list="[processImageUrl(selectedPush.coverImage)]"
            />
          </el-descriptions-item>
          <el-descriptions-item label="内容" :span="2">{{ selectedPush.content }}</el-descriptions-item>
          <el-descriptions-item label="发布者">{{ selectedPush.publisherName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(selectedPush.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="浏览次数">{{ selectedPush.viewCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="点赞数">{{ selectedPush.likeCount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="评论数">{{ selectedPush.commentCount || 0 }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 创建/编辑推文对话框 -->
    <el-dialog
      v-model="pushDialogVisible"
      :title="isEditPush ? '编辑推文' : '创建推文'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form 
        v-if="pushForm" 
        :model="pushForm" 
        :rules="pushFormRules"
        ref="pushFormRef"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="pushForm.title" 
            placeholder="请输入推文标题"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="简介" prop="summary">
          <el-input 
            v-model="pushForm.summary" 
            type="textarea" 
            :rows="3"
            placeholder="请输入推文简介"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="pushForm.content" 
            type="textarea" 
            :rows="8"
            placeholder="请输入推文详细内容"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="封面图片">
          <el-upload
            ref="coverUploadRef"
            :action="uploadAction"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :on-remove="handleCoverRemove"
            :on-error="handleCoverUploadError"
            :before-upload="beforeCoverUpload"
            accept="image/*"
            class="cover-uploader"
            name="cover"
          >
            <img v-if="pushForm.coverImage" :src="processImageUrl(pushForm.coverImage)" class="cover-image" />
            <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持jpg、png、gif格式，文件大小不超过5MB</div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="pushDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmPush"
            :loading="pushSubmitLoading"
          >
            {{ isEditPush ? '确认修改' : '确认创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="`${selectedAuditActivity?.name} - 医生报名审核`"
      width="1200px"
      :close-on-click-modal="false"
      @close="resetAuditData"
    >
      <div class="audit-content">
        <div class="audit-header">
          <div class="activity-info">
            <h4>{{ selectedAuditActivity?.name }}</h4>
            <p><strong>地点：</strong>{{ selectedAuditActivity?.location }}</p>
            <p><strong>积分：</strong><span class="points">{{ selectedAuditActivity?.points || 0 }} 分</span></p>
            <p><strong>时间：</strong>{{ formatDateTime(selectedAuditActivity?.startTime) }} - {{ formatDateTime(selectedAuditActivity?.endTime) }}</p>
          </div>
          <div class="batch-actions">
            <el-button 
              type="success" 
              :disabled="!selectedAuditRegistrations.length"
              @click="showBatchApproveDialog"
            >
              批量审核 ({{ selectedAuditRegistrations.length }})
            </el-button>
            <el-button @click="loadAuditRegistrations">刷新列表</el-button>
          </div>
        </div>

        <!-- 医生报名列表 -->
        <el-table
          :data="auditRegistrationsList"
          @selection-change="handleAuditSelectionChange"
          v-loading="auditRegistrationsLoading"
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="doctorName" label="医生姓名" width="120" />
          <el-table-column prop="hospitalName" label="医院名称" width="150" />
          <el-table-column prop="practiceScope" label="执业范围" width="120" />
          <el-table-column prop="registrationTime" label="报名时间" width="160">
            <template #default="{ row }">
              {{ formatDateTime(row.registrationTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag 
                :type="getAuditStatusType(row.status)"
                size="small"
              >
                {{ getAuditStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="pointsEarned" label="获得积分" width="100">
            <template #default="{ row }">
              <span class="points">{{ row.pointsEarned || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div v-if="row.status === 'REGISTERED'" class="action-buttons">
                <el-button 
                  type="success" 
                  size="small" 
                  @click="showApproveDialog(row)"
                >
                  审核
                </el-button>
              </div>
              <span v-else-if="row.status === 'COMPLETED'" class="completed-tag">
                <el-tag type="success" size="small">已完成</el-tag>
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="auditRegistrationsTotal > 0"
          v-model:current-page="auditRegistrationsCurrentPage"
          v-model:page-size="auditRegistrationsPageSize"
          :total="auditRegistrationsTotal"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleAuditSizeChange"
          @current-change="handleAuditCurrentChange"
          style="margin-top: 20px; text-align: right;"
        />
      </div>
    </el-dialog>

    <!-- 单个审核对话框 -->
    <el-dialog
      v-model="approveDialogVisible"
      title="审核医生报名"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="approve-content">
        <div class="doctor-info">
          <h4>医生信息</h4>
          <p><strong>姓名：</strong>{{ selectedAuditRegistration?.doctorName }}</p>
          <p><strong>医院：</strong>{{ selectedAuditRegistration?.hospitalName }}</p>
          <p><strong>执业范围：</strong>{{ selectedAuditRegistration?.practiceScope }}</p>
          <p><strong>报名时间：</strong>{{ formatDateTime(selectedAuditRegistration?.registrationTime) }}</p>
          <p v-if="selectedAuditRegistration?.remark"><strong>备注：</strong>{{ selectedAuditRegistration.remark }}</p>
        </div>

        <div class="activity-info">
          <h4>活动信息</h4>
          <p><strong>活动：</strong>{{ selectedAuditActivity?.name }}</p>
          <p><strong>预设积分：</strong><span class="points">{{ selectedAuditActivity?.points || 0 }} 分</span></p>
        </div>

        <el-form :model="approveForm" :rules="approveRules" ref="approveFormRef">
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="approveForm.status" placeholder="请选择状态">
              <el-option label="已完成" value="COMPLETED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="给予积分" prop="pointsEarned">
            <el-input-number 
              v-model="approveForm.pointsEarned" 
              :min="0" 
              :max="1000" 
              controls-position="right"
              placeholder="请输入积分"
              style="width: 200px"
            />
            <span style="margin-left: 10px; color: #909399; font-size: 12px;">
              建议：{{ selectedAuditActivity?.points || 0 }} 分
            </span>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approveDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmApprove"
            :loading="approveLoading"
          >
            确认审核
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量审核对话框 -->
    <el-dialog
      v-model="batchApproveDialogVisible"
      title="批量审核报名"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="batch-approve-content">
        <div class="batch-info">
          <h4>批量审核信息</h4>
          <p><strong>活动：</strong>{{ selectedAuditActivity?.name }}</p>
          <p><strong>选中医生：</strong>{{ selectedAuditRegistrations.length }} 人</p>
          <p><strong>活动积分：</strong><span class="points">{{ selectedAuditActivity?.points || 0 }} 分</span></p>
        </div>
        
        <el-form :model="batchApproveForm" :rules="batchApproveRules" ref="batchApproveFormRef">
          <el-form-item label="审核状态" prop="status">
            <el-select v-model="batchApproveForm.status" placeholder="请选择状态">
              <el-option label="已完成" value="COMPLETED" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="给予积分" prop="pointsEarned">
            <el-input-number 
              v-model="batchApproveForm.pointsEarned" 
              :min="0" 
              :max="1000" 
              controls-position="right"
              placeholder="请输入积分"
              style="width: 200px"
            />
            <span style="margin-left: 10px; color: #909399; font-size: 12px;">
              每人将获得此积分
            </span>
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchApproveDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmBatchApprove"
            :loading="batchApproveLoading"
          >
            确认批量审核
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, ChatDotRound } from '@element-plus/icons-vue'

import { 
  getDoctorsByAdmin, 
  createDoctor, 
  updateDoctor, 
  deleteDoctor, 
  batchDeleteDoctor,
  getDeletedDoctorsPage,
  restoreDoctor
} from '../api/doctor'
import { 
  getHospitalList,
  getActivityRegistrations,
  getActivityRegistrationStatistics,
  getDoctorRegistrationsByActivity,
  approveDoctorRegistration,
  batchApproveDoctorRegistrations
} from '../api/admin'
import { 
  getAdminActivityList, 
  createActivity, 
  updateActivity, 
  deleteActivity,
  uploadActivityCover
} from '../api/activity'
import { 
  createPush,
  updatePush,
  deletePush,
  batchDeletePush,
  publishPush,
  withdrawPush,
  getPushPage,
  getPushDetail,
  getPushList,
  uploadPushCover
} from '../api/push'
import { 
  getAdminNames,
  getProcessedFeedbacksByAdmin,
  getPendingFeedbacksByAdmin
} from '../api/feedback'

const router = useRouter()
const activeTab = ref('doctors')

// 医生管理相关
const doctorLoading = ref(false)
const doctorList = ref([])
const selectedDoctors = ref([])
const doctorDialogVisible = ref(false)
const isEditDoctor = ref(false)
const doctorSubmitLoading = ref(false)
const doctorFormRef = ref()
const hospitalList = ref([])

const doctorSearchForm = reactive({
  realName: '',
  phone: '',
  email: '',
  gender: '',
  practiceScope: '',
  level: '',
  hospitalName: ''
})

const doctorForm = reactive({
  username: '',
  password: '',
  realName: '',
  phone: '',
  email: '',
  gender: 1,
  address: '',
  practiceScope: '',
  hospitalName: ''
})

const doctorFormRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '用户名长度必须在3-10位之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '密码长度必须在6-15位之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入医生姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  hospitalName: [
    { required: true, message: '请选择所属医院', trigger: 'change' }
  ]
}

const doctorPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 已删除医生管理相关
const deletedDoctorsDialogVisible = ref(false)
const deletedDoctorsLoading = ref(false)
const deletedDoctorsList = ref([])
const deletedDoctorsPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})



// 活动管理相关
const activityLoading = ref(false)
const activityList = ref([])
const selectedActivities = ref([])
const activityDialogVisible = ref(false)
const isEditActivity = ref(false)
const activitySubmitLoading = ref(false)
const activityFormRef = ref()
const coverUploadRef = ref()
const coverFile = ref(null)

// 医生报名管理相关
const registrationsDialogVisible = ref(false)
const registrationsLoading = ref(false)
const registrationsList = ref([])
const selectedActivity = ref(null)
const registrationsCurrentPage = ref(1)
const registrationsPageSize = ref(10)
const registrationsTotal = ref(0)

// 审核功能相关
const auditDialogVisible = ref(false)
const selectedAuditActivity = ref(null)
const auditRegistrationsList = ref([])
const auditRegistrationsLoading = ref(false)
const selectedAuditRegistrations = ref([])
const auditRegistrationsCurrentPage = ref(1)
const auditRegistrationsPageSize = ref(10)
const auditRegistrationsTotal = ref(0)

// 单个审核对话框
const approveDialogVisible = ref(false)
const approveLoading = ref(false)
const selectedAuditRegistration = ref(null)
const approveFormRef = ref(null)

// 批量审核对话框
const batchApproveDialogVisible = ref(false)
const batchApproveLoading = ref(false)
const batchApproveFormRef = ref(null)

// 审核表单数据
const approveForm = reactive({
  status: '',
  pointsEarned: 0
})

const batchApproveForm = reactive({
  status: '',
  pointsEarned: 0
})

// 审核表单验证规则
const approveRules = {
  status: [
    { required: true, message: '请选择审核状态', trigger: 'change' }
  ],
  pointsEarned: [
    { required: true, message: '请输入积分', trigger: 'blur' },
    { type: 'number', min: 0, message: '积分不能小于0', trigger: 'blur' }
  ]
}

const batchApproveRules = {
  status: [
    { required: true, message: '请选择审核状态', trigger: 'change' }
  ],
  pointsEarned: [
    { required: true, message: '请输入积分', trigger: 'blur' },
    { type: 'number', min: 0, message: '积分不能小于0', trigger: 'blur' }
  ]
}

const activitySearchForm = reactive({
  name: '',
  location: '',
  startTime: '',
  endTime: ''
})

const activityForm = reactive({
  id: null,
  name: '',
  cover: '',
  description: '',
  location: '',
  startTime: '',
  endTime: '',
  points: 50
})

const activityFormRules = {
  name: [
    { required: true, message: '请输入活动名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入活动描述', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  points: [
    { required: true, message: '请设置活动积分', trigger: 'blur' },
    { type: 'number', min: 0, max: 1000, message: '积分范围为0-1000', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ]
}

// 审核表单已移除

const activityPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 推文管理相关
const pushLoading = ref(false)
const pushList = ref([])
const selectedPushes = ref([])
const pushDetailDialogVisible = ref(false)
const pushDialogVisible = ref(false)
const isEditPush = ref(false)
const pushSubmitLoading = ref(false)
const pushFormRef = ref()
const selectedPush = ref(null)

// 反馈管理相关
const feedbackStats = ref({
  total: 0,
  pending: 0,
  processing: 0,
  resolved: 0
})

const pushSearchForm = reactive({
  title: '',
  publisherName: '',
  status: '',
  startTime: '',
  endTime: ''
})

const pushForm = ref(null)

const pushFormRules = {
  title: [
    { required: true, message: '请输入推文标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度必须在1-100字符之间', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入推文简介', trigger: 'blur' },
    { min: 1, max: 200, message: '简介长度必须在1-200字符之间', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入推文内容', trigger: 'blur' },
    { min: 1, max: 5000, message: '内容长度必须在1-5000字符之间', trigger: 'blur' }
  ]
}

const pushPagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 图片上传相关
const uploadRef = ref()
const uploadAction = '/api/admin/push/uploadCover'
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${localStorage.getItem('adminToken')}`
}))

// 管理员信息
const adminInfo = reactive({
  realName: '管理员'
})

// 获取管理员信息
const fetchAdminInfo = () => {
  try {
    const adminInfoStr = localStorage.getItem('adminInfo')
    if (adminInfoStr) {
      const adminData = JSON.parse(adminInfoStr)
      Object.assign(adminInfo, adminData)
    }
  } catch (error) {
    console.error('获取管理员信息失败:', error)
    // 使用默认值
    adminInfo.realName = '管理员'
  }
}

// 计算属性
const doctorDialogTitle = computed(() => isEditDoctor.value ? '编辑医生' : '新增医生')
const activityDialogTitle = computed(() => isEditActivity.value ? '编辑活动' : '新增活动')
const pushDialogTitle = computed(() => isEditPush.value ? '编辑推文' : '新增推文')



// 获取医院列表
const fetchHospitalList = async () => {
  try {
    const response = await getHospitalList()
    if (response.code === 200) {
      hospitalList.value = response.data.hospitals || []
    }
  } catch (error) {
    console.error('获取医院列表失败:', error)
    ElMessage.error('获取医院列表失败')
  }
}

// 获取医生列表
const fetchDoctorList = async () => {
  try {
    doctorLoading.value = true
    const queryData = {
      realName: doctorSearchForm.realName,
      phone: doctorSearchForm.phone,
      email: doctorSearchForm.email,
      gender: doctorSearchForm.gender,
      practiceScope: doctorSearchForm.practiceScope,
      level: doctorSearchForm.level,
      current: doctorPagination.current,
      size: doctorPagination.size
    }
    
    const response = await getDoctorsByAdmin(queryData)
    
    if (response.code === 200) {
      doctorList.value = response.data.records
      doctorPagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取医生列表失败')
    }
  } catch (error) {
    console.error('获取医生列表失败:', error)
    ElMessage.error('获取医生列表失败，请检查网络连接')
  } finally {
    doctorLoading.value = false
  }
}

// 获取已删除医生列表
const fetchDeletedDoctors = async () => {
  try {
    deletedDoctorsLoading.value = true
    const pageDTO = { 
      current: deletedDoctorsPagination.current, 
      size: deletedDoctorsPagination.size 
    }
    
    const response = await getDeletedDoctorsPage(pageDTO)
    
    if (response.code === 200) {
      deletedDoctorsList.value = response.data.records
      deletedDoctorsPagination.total = response.data.total
    } else {
      ElMessage.error(response.message || '获取已删除医生列表失败')
    }
  } catch (error) {
    console.error('获取已删除医生列表失败:', error)
    ElMessage.error('获取已删除医生列表失败，请检查网络连接')
  } finally {
    deletedDoctorsLoading.value = false
  }
}



// 处理封面URL
const processCoverUrl = (url) => {
  if (!url) return ''
  
  // 如果已经是完整的URL，直接返回
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url
  }
  
  // 如果是MinIO的URL，直接返回
  if (url.includes('minio')) {
    return url
  }
  
  // 如果是相对路径，添加服务器基础URL
  if (url.startsWith('/')) {
    return `http://localhost:8080${url}`
  }
  
  // 如果URL已经包含了服务器地址，直接返回
  if (url.includes('localhost:8080')) {
    return url
  }
  
  // 根据后端API的配置，使用最可能的路径
  // 通常后端会将上传的文件放在 /uploads 目录下
  // 使用新的封面获取接口
  return `http://localhost:8080/activity/cover/${url}`
}

// 获取活动列表
const fetchActivityList = async () => {
  try {
    activityLoading.value = true
    const response = await getAdminActivityList()
    
    if (response.code === 200) {
      // 调试：打印活动数据
      console.log('活动列表数据:', response.data)
      
      // 处理每个活动的封面URL
      activityList.value = response.data.map(activity => ({
        ...activity,
        cover: processCoverUrl(activity.cover)
      }))
      
      activityPagination.total = response.data.length
      
      // 获取每个活动的报名统计信息
      await loadActivityRegistrationStatistics()
    } else {
      ElMessage.error(response.message || '获取活动列表失败')
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败，请检查网络连接')
  } finally {
    activityLoading.value = false
  }
}

// 加载活动报名统计信息
const loadActivityRegistrationStatistics = async () => {
  for (const activity of activityList.value) {
    try {
      const response = await getActivityRegistrationStatistics(activity.id)
      if (response.code === 200) {
        // 将后端返回的数据结构转换为前端期望的格式
        const backendData = response.data
        activity.registrationStats = {
          totalRegistrations: backendData.totalCount || 0,
          attendedCount: 0, // 后端暂时没有提供这些字段，设为0
          completedCount: 0  // 后端暂时没有提供这些字段，设为0
        }
        console.log(`活动 ${activity.id} 统计信息:`, activity.registrationStats)
      }
    } catch (error) {
      console.error(`获取活动 ${activity.id} 报名统计失败:`, error)
      activity.registrationStats = { totalRegistrations: 0, attendedCount: 0, completedCount: 0 }
    }
  }
}



// 医生搜索
const handleDoctorSearch = () => {
  doctorPagination.current = 1
  fetchDoctorList()
}

// 重置医生搜索
const resetDoctorSearch = () => {
  Object.assign(doctorSearchForm, {
    realName: '',
    phone: '',
    email: '',
    gender: '',
    practiceScope: '',
    level: '',
    hospitalName: ''
  })
  doctorPagination.current = 1
  fetchDoctorList()
}

// 活动搜索
const handleActivitySearch = () => {
  // 由于后端API没有分页和搜索功能，这里只是简单的客户端过滤
  fetchActivityList()
}

// 重置活动搜索
const resetActivitySearch = () => {
  Object.assign(activitySearchForm, {
    name: '',
    location: '',
    startTime: '',
    endTime: ''
  })
  fetchActivityList()
}



// 医生选择变化
const handleDoctorSelectionChange = (selection) => {
  selectedDoctors.value = selection
}

// 活动选择变化
const handleActivitySelectionChange = (selection) => {
  selectedActivities.value = selection
}

// 显示创建医生对话框
const showCreateDoctorDialog = () => {
  isEditDoctor.value = false
  // 自动设置所属医院为当前管理员的真实姓名
  doctorForm.hospitalName = adminInfo.realName
  doctorDialogVisible.value = true
}

// 显示编辑医生对话框
const showEditDoctorDialog = (row) => {
  isEditDoctor.value = true
  Object.assign(doctorForm, row)
  doctorDialogVisible.value = true
}

// 重置医生表单
const resetDoctorForm = () => {
  Object.assign(doctorForm, {
    username: '',
    password: '',
    realName: '',
    phone: '',
    email: '',
    gender: 1,
    address: '',
    practiceScope: '',
    hospitalName: adminInfo.realName || '' // 重置时也自动设置为当前管理员
  })
  if (doctorFormRef.value) {
    doctorFormRef.value.resetFields()
  }
}

// 显示创建活动对话框
const showCreateActivityDialog = () => {
  isEditActivity.value = false
  activityDialogVisible.value = true
}

// 显示编辑活动对话框
const showEditActivityDialog = (row) => {
  isEditActivity.value = true
  Object.assign(activityForm, {
    id: row.id,
    name: row.name,
    cover: processCoverUrl(row.cover),
    description: row.description,
    location: row.location,
    startTime: row.startTime,
    endTime: row.endTime,
    points: row.points || 50
  })
  activityDialogVisible.value = true
}

// 重置活动表单
const resetActivityForm = () => {
  Object.assign(activityForm, {
    id: null,
    name: '',
    cover: '',
    description: '',
    location: '',
    startTime: '',
    endTime: '',
    points: 50
  })
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
  // 重置封面文件
  coverFile.value = null
  if (coverUploadRef.value) {
    coverUploadRef.value.clearFiles()
  }
}

// 处理封面文件选择
const handleCoverChange = (file) => {
  // 验证文件类型
  const isValidType = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp'].includes(file.raw.type)
  if (!isValidType) {
    ElMessage.error('只支持 jpg, jpeg, png, gif, bmp 格式的图片')
    return false
  }
  
  // 验证文件大小（5MB）
  const isLt5M = file.raw.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('文件大小不能超过 5MB')
    return false
  }
  
  // 保存文件并显示预览
  coverFile.value = file.raw
  activityForm.cover = URL.createObjectURL(file.raw)
  return false // 阻止自动上传
}

// 提交医生表单
const handleDoctorSubmit = async () => {
  if (!doctorFormRef.value) return
  
  try {
    await doctorFormRef.value.validate()
    doctorSubmitLoading.value = true
    
    let response
    if (isEditDoctor.value) {
      response = await updateDoctor(doctorForm)
    } else {
      response = await createDoctor(doctorForm)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEditDoctor.value ? '更新成功' : '创建成功')
      doctorDialogVisible.value = false
      fetchDoctorList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请检查网络连接')
  } finally {
    doctorSubmitLoading.value = false
  }
}

// 提交活动表单
const handleActivitySubmit = async () => {
  if (!activityFormRef.value) return
  
  try {
    await activityFormRef.value.validate()
    activitySubmitLoading.value = true
    
    // 验证时间
    if (activityForm.startTime && activityForm.endTime) {
      if (new Date(activityForm.startTime) >= new Date(activityForm.endTime)) {
        ElMessage.error('开始时间不能晚于或等于结束时间')
        return
      }
    }
    
    let response
    if (isEditActivity.value) {
      response = await updateActivity(activityForm)
    } else {
      response = await createActivity(activityForm)
    }
    
    if (response.code === 200) {
      console.log('活动操作成功，响应数据:', response.data)
      
      // 如果有封面文件，上传封面
      if (coverFile.value) {
        try {
          console.log('开始上传封面文件...')
          const uploadResponse = await uploadActivityCover(response.data.id, coverFile.value)
          console.log('封面上传响应:', uploadResponse)
          if (uploadResponse.code === 200) {
            // 更新活动封面URL
            activityForm.cover = uploadResponse.data.coverUrl
            console.log('更新后的封面URL:', activityForm.cover)
            await updateActivity(activityForm)
          }
        } catch (uploadError) {
          console.error('封面上传失败:', uploadError)
          ElMessage.warning('活动创建成功，但封面上传失败')
        }
      } else if (isEditActivity.value && activityForm.cover) {
        // 编辑时，如果没有新文件但有封面URL，确保封面URL被保存
        console.log('编辑模式，保持现有封面URL:', activityForm.cover)
        try {
          await updateActivity(activityForm)
        } catch (updateError) {
          console.error('更新活动封面失败:', updateError)
          ElMessage.warning('活动更新成功，但封面更新失败')
        }
      }
      
      ElMessage.success(isEditActivity.value ? '更新成功' : '创建成功')
      activityDialogVisible.value = false
      fetchActivityList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请检查网络连接')
  } finally {
    activitySubmitLoading.value = false
  }
}



// 删除医生
const handleDeleteDoctor = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个医生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteDoctor(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchDoctorList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 删除活动
const handleDeleteActivity = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个活动吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deleteActivity(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchActivityList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}



// 批量删除医生
const handleBatchDeleteDoctor = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedDoctors.value.length} 个医生吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const doctorIds = selectedDoctors.value.map(doctor => doctor.id)
    const response = await batchDeleteDoctor(doctorIds)
    
    if (response.code === 200) {
      ElMessage.success('批量删除成功')
      selectedDoctors.value = []
      fetchDoctorList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请检查网络连接')
    }
  }
}

// 批量删除活动
const handleBatchDeleteActivity = async () => {
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedActivities.value.length} 个活动吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 逐个删除活动（因为后端没有批量删除接口）
    const deletePromises = selectedActivities.value.map(activity => deleteActivity(activity.id))
    await Promise.all(deletePromises)
    
    ElMessage.success('批量删除成功')
    selectedActivities.value = []
    fetchActivityList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败，请检查网络连接')
    }
  }
}

// 恢复医生
const handleRestoreDoctor = async (doctorId) => {
  try {
    await ElMessageBox.confirm('确定要恢复这个医生吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await restoreDoctor(doctorId)
    
    if (response.code === 200) {
      ElMessage.success('恢复成功')
      fetchDeletedDoctors()
    } else {
      ElMessage.error(response.message || '恢复失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复失败:', error)
      ElMessage.error('恢复失败，请检查网络连接')
    }
  }
}







// 医生分页处理
const handleDoctorSizeChange = (size) => {
  doctorPagination.size = size
  doctorPagination.current = 1
  fetchDoctorList()
}

const handleDoctorCurrentChange = (current) => {
  doctorPagination.current = current
  fetchDoctorList()
}

// 已删除医生分页处理
const handleDeletedDoctorsSizeChange = (size) => {
  deletedDoctorsPagination.size = size
  deletedDoctorsPagination.current = 1
  fetchDeletedDoctors()
}

const handleDeletedDoctorsCurrentChange = (current) => {
  deletedDoctorsPagination.current = current
  fetchDeletedDoctors()
}



// 活动分页处理
const handleActivitySizeChange = (size) => {
  activityPagination.size = size
  activityPagination.current = 1
  // 由于后端API没有分页，这里只是更新本地分页状态
}

const handleActivityCurrentChange = (current) => {
  activityPagination.current = current
  // 由于后端API没有分页，这里只是更新本地分页状态
}



// 查看已删除医生
const showDeletedDoctors = () => {
  deletedDoctorsDialogVisible.value = true
  fetchDeletedDoctors()
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    localStorage.removeItem('adminToken')
    localStorage.removeItem('level')
    localStorage.removeItem('adminInfo')
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch {
    // 用户取消
  }
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN')
}



// 处理图片加载错误
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  
  // 直接显示加载失败
  event.target.style.display = 'none'
  const errorSpan = event.target.parentElement.querySelector('.image-error')
  if (errorSpan) {
    errorSpan.style.display = 'inline'
  }
}

// 组件挂载时获取数据
// ==================== 医生报名管理相关方法 ====================

// 显示报名管理对话框
const showRegistrationsDialog = async (activity) => {
  selectedActivity.value = activity
  registrationsDialogVisible.value = true
  await loadRegistrations()
}

// 加载活动报名列表
const loadRegistrations = async () => {
  if (!selectedActivity.value) return
  
  registrationsLoading.value = true
  try {
    // 使用新的API接口获取报名列表
    const response = await getActivityRegistrations(selectedActivity.value.id)
    
    if (response.code === 200) {
      registrationsList.value = response.data || []
      registrationsTotal.value = response.data?.length || 0
    } else {
      ElMessage.error(response.message || '获取报名列表失败')
    }
  } catch (error) {
    console.error('获取报名列表失败:', error)
    ElMessage.error('获取报名列表失败')
  } finally {
    registrationsLoading.value = false
  }
}

// 重置报名数据
const resetRegistrations = () => {
  registrationsList.value = []
  registrationsCurrentPage.value = 1
  registrationsTotal.value = 0
}

// ==================== 审核相关方法 ====================

// 显示审核对话框
const showAuditDialog = async (activity) => {
  selectedAuditActivity.value = activity
  selectedAuditRegistrations.value = []
  auditRegistrationsCurrentPage.value = 1
  auditDialogVisible.value = true
  await loadAuditRegistrations()
}

// 加载审核报名列表
const loadAuditRegistrations = async () => {
  if (!selectedAuditActivity.value) return
  
  auditRegistrationsLoading.value = true
  try {
    const params = {
      current: auditRegistrationsCurrentPage.value,
      size: auditRegistrationsPageSize.value
    }
    
    const response = await getDoctorRegistrationsByActivity(selectedAuditActivity.value.id, params)
    
    if (response.code === 200) {
      auditRegistrationsList.value = response.data.records || []
      auditRegistrationsTotal.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取报名列表失败')
    }
  } catch (error) {
    console.error('获取报名列表失败:', error)
    ElMessage.error('获取报名列表失败')
  } finally {
    auditRegistrationsLoading.value = false
  }
}

// 处理审核选择变化
const handleAuditSelectionChange = (selections) => {
  selectedAuditRegistrations.value = selections
}

// 显示单个审核对话框
const showApproveDialog = (registration) => {
  selectedAuditRegistration.value = registration
  approveForm.status = 'COMPLETED'
  approveForm.pointsEarned = selectedAuditActivity.value?.points || 50
  approveDialogVisible.value = true
}

// 确认单个审核
const confirmApprove = async () => {
  if (!approveFormRef.value) return
  
  await approveFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    approveLoading.value = true
    try {
      const response = await approveDoctorRegistration(selectedAuditRegistration.value.id, {
        status: approveForm.status,
        pointsEarned: approveForm.pointsEarned
      })
      
      if (response.code === 200) {
        ElMessage.success('审核成功!')
        approveDialogVisible.value = false
        await loadAuditRegistrations()
      } else {
        ElMessage.error(response.message || '审核失败')
      }
    } catch (error) {
      console.error('审核失败:', error)
      ElMessage.error('审核失败')
    } finally {
      approveLoading.value = false
    }
  })
}

// 显示批量审核对话框
const showBatchApproveDialog = () => {
  if (selectedAuditRegistrations.value.length === 0) {
    ElMessage.warning('请先选择要审核的报名记录')
    return
  }
  
  batchApproveForm.status = 'COMPLETED'
  batchApproveForm.pointsEarned = selectedAuditActivity.value?.points || 50
  batchApproveDialogVisible.value = true
}

// 确认批量审核
const confirmBatchApprove = async () => {
  if (!batchApproveFormRef.value) return
  
  await batchApproveFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    batchApproveLoading.value = true
    try {
      const registrationIds = selectedAuditRegistrations.value.map(item => item.id)
      
      const response = await batchApproveDoctorRegistrations({
        registrationIds: registrationIds,
        status: batchApproveForm.status,
        pointsEarned: batchApproveForm.pointsEarned
      })
      
      if (response.code === 200) {
        ElMessage.success('批量审核成功!')
        batchApproveDialogVisible.value = false
        await loadAuditRegistrations()
      } else {
        ElMessage.error(response.message || '批量审核失败')
      }
    } catch (error) {
      console.error('批量审核失败:', error)
      ElMessage.error('批量审核失败')
    } finally {
      batchApproveLoading.value = false
    }
  })
}

// 审核分页处理
const handleAuditSizeChange = (size) => {
  auditRegistrationsPageSize.value = size
  loadAuditRegistrations()
}

const handleAuditCurrentChange = (page) => {
  auditRegistrationsCurrentPage.value = page
  loadAuditRegistrations()
}

// 获取审核状态类型
const getAuditStatusType = (status) => {
  const statusMap = {
    'REGISTERED': 'info',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取审核状态文本
const getAuditStatusText = (status) => {
  const statusMap = {
    'REGISTERED': '已报名',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  }
  return statusMap[status] || status
}

// 重置审核数据
const resetAuditData = () => {
  auditRegistrationsList.value = []
  selectedAuditRegistrations.value = []
  auditRegistrationsCurrentPage.value = 1
  auditRegistrationsTotal.value = 0
}

// 报名分页处理
const handleRegistrationsSizeChange = (size) => {
  registrationsPageSize.value = size
  loadRegistrations()
}

const handleRegistrationsCurrentChange = (page) => {
  registrationsCurrentPage.value = page
  loadRegistrations()
}




// 刷新当前标签页
const refreshCurrentTab = () => {
  if (activeTab.value === 'doctors') {
    fetchDoctorList()
  } else if (activeTab.value === 'activities') {
    fetchActivityList()
  } else if (activeTab.value === 'push') {
    fetchPushList()
  } else if (activeTab.value === 'feedback') {
    refreshFeedbackData()
  }
  ElMessage.success('刷新成功')
}

// 反馈管理相关函数
const goToFeedbackManagement = () => {
  router.push('/feedback-management')
}

const refreshFeedbackData = async () => {
  try {
    // 获取当前管理员信息
    const adminInfo = JSON.parse(localStorage.getItem('adminInfo') || '{}')
    const currentAdminId = adminInfo.id
    
    if (!currentAdminId) {
      ElMessage.error('未找到管理员信息')
      return
    }
    
    // 获取待处理和已处理的反馈数据
    const [pendingResponse, processedResponse] = await Promise.all([
      getPendingFeedbacksByAdmin(currentAdminId),
      getProcessedFeedbacksByAdmin(currentAdminId)
    ])
    
    if (pendingResponse.code === 200 && processedResponse.code === 200) {
      const pendingFeedbacks = pendingResponse.data || []
      const processedFeedbacks = processedResponse.data || []
      
      // 计算统计数据
      const total = pendingFeedbacks.length + processedFeedbacks.length
      const pending = pendingFeedbacks.filter(f => f.status === 'PENDING').length
      const processing = pendingFeedbacks.filter(f => f.status === 'PROCESSING').length
      const resolved = processedFeedbacks.filter(f => f.status === 'RESOLVED').length
      
      feedbackStats.value = {
        total,
        pending,
        processing,
        resolved
      }
    } else {
      ElMessage.error('获取反馈数据失败')
    }
  } catch (error) {
    console.error('获取反馈统计失败:', error)
    ElMessage.error('获取反馈统计失败')
  }
}

// ==================== 推文管理相关方法 ====================

// 获取推文列表
const fetchPushList = async () => {
  try {
    pushLoading.value = true
    const params = {
      current: pushPagination.current,
      size: pushPagination.size,
      ...pushSearchForm
    }
    
    console.log('获取推文列表参数:', params)
    const response = await getPushPage(params)
    console.log('推文列表响应:', response)
      
      if (response.code === 200) {
      pushList.value = response.data.records || []
      pushPagination.total = response.data.total || 0
      console.log('推文列表数据:', pushList.value)
      } else {
      ElMessage.error(response.message || '获取推文列表失败')
      }
    } catch (error) {
    console.error('获取推文列表失败:', error)
    ElMessage.error('获取推文列表失败，请检查网络连接')
    } finally {
    pushLoading.value = false
  }
}

// 推文搜索
const handlePushSearch = () => {
  pushPagination.current = 1
  fetchPushList()
}

// 重置推文搜索
const resetPushSearch = () => {
  Object.assign(pushSearchForm, {
    title: '',
    publisherName: '',
    status: '',
    startTime: '',
    endTime: ''
  })
  pushPagination.current = 1
  fetchPushList()
}

// 推文分页处理
const handlePushSizeChange = (size) => {
  pushPagination.size = size
  pushPagination.current = 1
  fetchPushList()
}

const handlePushCurrentChange = (current) => {
  pushPagination.current = current
  fetchPushList()
}

// 推文选择变化
const handlePushSelectionChange = (selection) => {
  selectedPushes.value = selection
}

// 显示推文详情
const showPushDetail = (push) => {
  selectedPush.value = push
  pushDetailDialogVisible.value = true
}

// 显示创建推文对话框
const showCreatePushDialog = () => {
  isEditPush.value = false
  pushForm.value = {
    title: '',
    summary: '',
    content: '',
    coverImage: '',
    status: 0
  }
  pushDialogVisible.value = true
}

// 显示编辑推文对话框
const showEditPushDialog = (push) => {
  isEditPush.value = true
  pushForm.value = {
    id: push.id,
    title: push.title,
    summary: push.summary,
    content: push.content,
    coverImage: push.coverImage || '',
    status: push.status
  }
  pushDialogVisible.value = true
}

// 确认推文操作
const confirmPush = async () => {
  if (!pushFormRef.value) return
  
  try {
    await pushFormRef.value.validate()
    pushSubmitLoading.value = true
    
    const formData = { ...pushForm.value }
    
    let response
    if (isEditPush.value) {
      response = await updatePush(formData)
    } else {
      response = await createPush(formData)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEditPush.value ? '推文修改成功' : '推文创建成功')
      pushDialogVisible.value = false
      pushForm.value = null
      fetchPushList()
    } else {
      ElMessage.error(response.message || '操作失败')
    }
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    pushSubmitLoading.value = false
  }
}

// 发布推文
const handlePublishPush = async (push) => {
  try {
    await ElMessageBox.confirm('确定要发布这个推文吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await publishPush(push.id)
    
    if (response.code === 200) {
      ElMessage.success('推文发布成功')
      fetchPushList()
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布推文失败:', error)
      ElMessage.error('发布推文失败')
    }
  }
}

// 撤回推文
const handleWithdrawPush = async (push) => {
  try {
    await ElMessageBox.confirm('确定要撤回这个推文吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await withdrawPush(push.id)
    
    if (response.code === 200) {
      ElMessage.success('推文撤回成功')
      fetchPushList()
    } else {
      ElMessage.error(response.message || '撤回失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回推文失败:', error)
      ElMessage.error('撤回推文失败')
    }
  }
}

// 删除推文
const handleDeletePush = async (push) => {
  try {
    await ElMessageBox.confirm('确定要删除这个推文吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deletePush(push.id)
    
    if (response.code === 200) {
      ElMessage.success('推文删除成功')
      fetchPushList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除推文失败:', error)
      ElMessage.error('删除推文失败')
    }
  }
}

// 批量删除推文
const handleBatchDeletePush = async () => {
  if (selectedPushes.value.length === 0) {
    ElMessage.warning('请选择要删除的推文')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedPushes.value.length} 个推文吗？`,
      '提示',
      { type: 'warning' }
    )
    
    const ids = selectedPushes.value.map(push => push.id)
    const response = await batchDeletePush(ids)
      
      if (response.code === 200) {
      ElMessage.success('批量删除成功')
      selectedPushes.value = []
      fetchPushList()
      } else {
      ElMessage.error(response.message || '批量删除失败')
      }
    } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 推文状态相关方法
const getPushStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'warning'
    default: return 'info'
  }
}

const getPushStatusText = (status) => {
  switch (status) {
    case 0: return '草稿'
    case 1: return '已发布'
    case 2: return '已撤回'
    default: return '未知'
  }
}

// 图片处理相关方法
const processImageUrl = (url) => {
  if (!url) return ''
  if (url.startsWith('http')) return url
  return `http://localhost:8080${url}`
}

// 封面上传相关方法
const handleCoverSuccess = (response, file, fileList) => {
  if (response.code === 200) {
    ElMessage.success('封面上传成功')
    // 更新表单中的封面
    if (pushForm.value) {
      pushForm.value.coverImage = response.data.coverUrl || response.data
    }
  } else {
    ElMessage.error(response.message || '封面上传失败')
  }
}

const handleCoverRemove = (file, fileList) => {
  if (pushForm.value) {
    pushForm.value.coverImage = null
  }
}

const handleCoverUploadError = (error, file, fileList) => {
  console.error('封面上传失败:', error)
  ElMessage.error('封面上传失败，请重试')
}

const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  return true
}

onMounted(() => {
  fetchAdminInfo()
  fetchHospitalList()
  fetchDoctorList()
  fetchActivityList()
  fetchPushList()
  refreshFeedbackData()
})
</script>

<style scoped>
.normal-admin-container {
  height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.header-left {
  flex: 1;
}

.header-center {
  flex: 0 0 auto;
  margin: 0 20px;
}

.header-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 15px;
}

.header-left h2 {
  margin: 0;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.welcome {
  color: #606266;
  font-size: 14px;
}

.main-content {
  padding: 20px;
}

.admin-tabs {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}

.tab-content {
  margin-top: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-area {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.action-area {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__content) {
  padding: 0;
}

.deleted-doctors-content {
  padding: 20px 0;
}

.deleted-doctors-content .pagination {
  margin-top: 20px;
  text-align: right;
}

/* 封面上传样式 */
.cover-upload {
  display: flex;
  align-items: flex-start;
  gap: 20px;
}

.cover-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.cover-uploader:hover {
  border-color: #409eff;
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 90px;
  line-height: 90px;
  text-align: center;
}

.cover-image {
  width: 120px;
  height: 90px;
  display: block;
  object-fit: cover;
}

.cover-tips {
  flex: 1;
  color: #909399;
  font-size: 12px;
  line-height: 1.5;
}

.cover-tips p {
  margin: 0 0 5px 0;
}

/* 报名管理样式 */
.registrations-content {
  padding: 0;
}

.registrations-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.registrations-header .activity-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 16px;
}

.registrations-header .activity-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.action-buttons .el-button {
  padding: 5px 8px;
}

.approve-info, .batch-approve-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.approve-info p, .batch-approve-info p {
  margin: 5px 0;
  color: #606266;
}

.points {
  color: #f56c6c;
  font-weight: bold;
}

/* 推文管理样式 */
.push-detail {
  padding: 20px 0;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 90px;
  line-height: 90px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 120px;
  height: 90px;
}

/* 推文状态标签样式 */
.push-status-tag {
  font-weight: 500;
}

/* 推文表格中的图片样式 */
.push-image-container {
  position: relative;
  display: inline-block;
}

.push-image {
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

/* 审核对话框样式 */
.audit-content {
  padding: 0;
}

.audit-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.audit-header .activity-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 16px;
}

.audit-header .activity-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.audit-header .batch-actions {
  display: flex;
  gap: 10px;
}

.approve-content, .batch-approve-content {
  padding: 0;
}

.doctor-info, .activity-info, .batch-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.doctor-info h4, .activity-info h4, .batch-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
  font-size: 16px;
}

.doctor-info p, .activity-info p, .batch-info p {
  margin: 5px 0;
  color: #606266;
}

.completed-tag {
  display: flex;
  justify-content: center;
}

/* 反馈管理样式 */
.feedback-management-content {
  padding: 20px;
}

.feedback-header {
  margin-bottom: 20px;
}

.feedback-header h3 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 20px;
}

.feedback-header p {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.feedback-actions {
  margin-bottom: 30px;
  display: flex;
  gap: 10px;
}

.feedback-stats {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-content {
  padding: 20px;
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
  color: #409eff;
}

.stat-number.pending {
  color: #e6a23c;
}

.stat-number.processing {
  color: #409eff;
}

.stat-number.resolved {
  color: #67c23a;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}
</style> 

